#!/usr/bin/env python3.11
# -*- encoding: utf-8 -*-
'''
@File    :   mixins.py
@Time    :   2024/05/28 18:10:12
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from typing import Any
from django.db.models import QuerySet

from .models import Role,Users
from apps.menus.models import MenuModel



class RoleViewMixin:
    request: Any
    
    def get_queryset(self) -> QuerySet:
        """
        获取查询集。如果当前请求的用户是超级用户，则返回所有对象的查询集，
        否则，返回当前请求用户拥有的所有对象的查询集。
        :return: Role对象的查询集
        """
        if hasattr(self.context.request, "user") and self.context.request.user.is_superuser:
            return Role.objects.all()
        # return Role.objects.filter(creator=self.context.request.user)
        return Role.objects.all()
    
    def get_menus_by_role_id(self, rid: int):
        """
        检查给定的角色的菜单权限
        :param rid: 角色id
        :return: 菜单列表
        """
        role = self.get_object_or_exception(
            self.get_queryset(), id=rid, error_message="角色不存在"
        )
        menus = MenuModel.objects.filter(id__in=role.menus.values_list("menu_id", flat=True))
        return menus

    
    
class UserViewMixin:
    request: Any
    def get_queryset(self) -> QuerySet:
        return Users.objects.all()